﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KL.UFrame.Core.Configuration;
using KL.UFrame.Core.Exception;
using KL.UFrame.Data.Entities;

namespace KL.UFrame.Data.Business.Impl
{
    public class ReportBusiness:BusinessBase,IReportBusiness
    {
        public async Task<List<Report>> GetAllAsync(bool onlyEnabled = true)
        {
            return await Db.Reports.Where(a => (onlyEnabled && a.Enabled) || !onlyEnabled).AsNoTracking()
                .ToListAsync();
        }

        public async Task<DataTable> ExportAsync(int reportId, DateTime start, DateTime end)
        {
            var report = await Db.Reports.FindAsync(reportId);
            if (report == null) throw new ResultException(-1, "报表不存在");
            if (!report.Enabled) throw new ResultException(-2, "报表不可用");

            var sqlFile = AppConfiguration.SqlTextPath + reportId + ".sql";
            if (!File.Exists(sqlFile)) throw new ResultException(-3, "报表统计脚本文件不存在");

            var sqlText = "";

            using (var reader = new StreamReader(sqlFile, Encoding.Default))
            {
                sqlText = await reader.ReadToEndAsync();
            }

            sqlText = string.Format(sqlText, start.ToString("yyyy-MM-dd"), end.ToString("yyyy-MM-dd 23:59:59"));
            var table = new DataTable
            {
                TableName = $"{report.Name}_{start.ToString("yyyy-MM-dd")}_{end.ToString("yyyy-MM-dd")}"
            };

            using (var conn =new SqlConnection(AppConfiguration.DbConnectionString))
            using (var cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandText = sqlText;
                cmd.CommandTimeout = 600;
                var sda = new SqlDataAdapter(cmd);
                sda.Fill(table);
            }
            return table;
        }

    }
}